package cn.leftshine.readme.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jaeger.ninegridimageview.ItemImageClickListener;
import com.jaeger.ninegridimageview.NineGridImageView;
import com.jaeger.ninegridimageview.NineGridImageViewAdapter;
import com.maning.imagebrowserlibrary.MNImageBrowser;
import com.maning.imagebrowserlibrary.MNImageBrowserActivity;
import com.maning.imagebrowserlibrary.listeners.OnClickListener;
import com.maning.imagebrowserlibrary.listeners.OnLongClickListener;
import com.maning.imagebrowserlibrary.listeners.OnPageChangeListener;
import com.maning.imagebrowserlibrary.model.ImageBrowserConfig;
import com.rometools.rome.feed.synd.SyndEntry;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.FileProvider;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.leftshine.readme.BuildConfig;
import cn.leftshine.readme.R;
import cn.leftshine.readme.beans.NewsItem;
import cn.leftshine.readme.event.NewsItemEvent;
import cn.leftshine.readme.helper.GlideImageEngine;
import cn.leftshine.readme.utils.FileUtils;
import cn.leftshine.readme.view.DownLoadProgressbar;
import solid.ren.skinlibrary.utils.SkinFileUtils;

import static android.app.Activity.RESULT_OK;


public class ImageRecyclerViewAdapter extends RecyclerView.Adapter<ImageRecyclerViewAdapter.ViewHolder> {

    private ArrayList<NewsItem> mValues;

    private Context mContext;
    private TextView tv_download_progress;
    private DownLoadProgressbar pb_download;

    public ImageRecyclerViewAdapter(ArrayList<NewsItem> items, Context context) {
        this.mContext = context;
        mValues = items;
    }

    public void update(ArrayList<NewsItem> items){
        mValues=items;
        notifyDataSetChanged();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        /*View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_image_item, parent, false);*/
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_image_nine_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.mItem = mValues.get(position);
        SyndEntry syndEntry = holder.mItem.getSyndEntry();
        holder.image_item_title.setText(syndEntry.getTitle());
        if(null!=syndEntry.getPublishedDate()) {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            holder.image_item_time.setText(sdf.format(syndEntry.getPublishedDate()));
        }else{
            holder.image_item_time.setText("");
        }
        holder.image_item_comment.setText(syndEntry.getComments());
        String description = syndEntry.getDescription().getValue();
        //List<String> imgList = getImgSrcList(description);
        ArrayList<String> imgList = holder.mItem.getImgList();
        if(imgList.size()>0) {
            holder.image_item_nine.setVisibility(View.VISIBLE);
            holder.image_item_nine.setImagesData(imgList);
        }
        else{
            holder.image_item_nine.setVisibility(View.GONE);
            //holder.image_item_time.setVisibility(View.GONE);
        }
        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //用eventBus
                EventBus.getDefault().post(new NewsItemEvent(holder.mItem));
            }
        });
    }



    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView image_item_title,image_item_time,image_item_comment;
        public final NineGridImageView image_item_nine;
        public NewsItem mItem;
        private NineGridImageViewAdapter<String> nineGridImageViewAdapter = new NineGridImageViewAdapter<String>() {
            @Override
            protected void onDisplayImage(Context context, ImageView imageView, String s) {
                Glide.with(context)
                        .load(s)
                        //.placeholder(R.drawable.ic_default_image)
                        .into(imageView);
            }

            @Override
            protected ImageView generateImageView(Context context) {
                return super.generateImageView(context);
            }

            @Override
            protected void onItemImageClick(Context context, ImageView imageView, int index, List<String> list) {
                //  Toast.makeText(context, "image position is " + index, Toast.LENGTH_SHORT).show();
            }
        };

        public ViewHolder(View view) {
            super(view);
            mView = view;
            image_item_nine = view.findViewById(R.id.image_item_nine);
            image_item_title = view.findViewById(R.id.image_item_title);

            image_item_time = view.findViewById(R.id.image_item_time);
            image_item_comment = view.findViewById(R.id.image_item_comment);

            image_item_nine.setAdapter(nineGridImageViewAdapter);

            image_item_nine.setItemImageClickListener(new ItemImageClickListener<String>() {
                @Override
                public void onItemImageClick(final Context context, final ImageView imageView, final int index, final List<String> list) {
                    final ArrayList<String> imgSrcList = new ArrayList<>();
                    for(String imgSrc:list){
                        imgSrcList.add(imgSrc);
                    }
                    /* 不支持GIF，改为使用MNImageBrowser
                    ImageInfo imageInfo;
                    final List<ImageInfo> imageInfoList = new ArrayList<>();
                    for (String image : list) {
                        imageInfo = new ImageInfo();
                        // 原图地址（必填）
                        imageInfo.setOriginUrl(image);
                        // 缩略图地址（必填）
                        // 如果没有缩略图url，可以将两项设置为一样。（注意：此处作为演示用，加了-1200，你们不要这么做）
                        imageInfo.setThumbnailUrl(image);
                        imageInfoList.add(imageInfo);
                        imageInfo = null;
                    }
                    ImagePreview
                            .getInstance()
                            .setContext(context)
                            .setImageInfoList(imageInfoList)
                            .setIndex(index)
                            .setShowDownButton(true)
                            .setLoadStrategy(ImagePreview.LoadStrategy.Default)
                            .setFolderName("ReadMeDownload")
                            .setScaleLevel(1, 3, 8)
                            .setZoomTransitionDuration(500)
                            .setEnableClickClose(true)// 是否启用点击图片关闭。默认启用
                            .setEnableDragClose(true)// 是否启用上拉/下拉关闭。默认不启用

                            .setShowCloseButton(true)// 是否显示关闭页面按钮，在页面左下角。默认显示
                            .setCloseIconResId(R.drawable.ic_action_close)// 设置关闭按钮图片资源，可不填，默认为：R.drawable.ic_action_close

                            .setShowDownButton(true)// 是否显示下载按钮，在页面右下角。默认显示
                            .setDownIconResId(R.drawable.icon_download_new)// 设置下载按钮图片资源，可不填，默认为：R.drawable.icon_download_new
                            .setShowIndicator(true)// 设置是否显示顶部的指示器（1/9）。默认显示
                            .start();*/

                    ImageBrowserConfig.TransformType transformType = ImageBrowserConfig.TransformType.Transform_Default;
                    ImageBrowserConfig.IndicatorType indicatorType = ImageBrowserConfig.IndicatorType.Indicator_Number;
                    ImageBrowserConfig.ScreenOrientationType screenOrientationType = ImageBrowserConfig.ScreenOrientationType.Screenorientation_Default;
                    Boolean showCustomShadeView = true;
                    Boolean showCustomProgressView =true;
                    final View customView = LayoutInflater.from(context).inflate(R.layout.layout_custom_image_show_view, null);
                    ImageView ic_close = (ImageView) customView.findViewById(R.id.iv_close);
                    ImageView iv_more = (ImageView) customView.findViewById(R.id.iv_more);
                    /*
                    ImageView iv_comment = (ImageView) customView.findViewById(R.id.iv_comment);
                    ImageView iv_zan = (ImageView) customView.findViewById(R.id.iv_zan);
                    ImageView iv_delete = (ImageView) customView.findViewById(R.id.iv_delete);*/
                    final ImageView iv_download = customView.findViewById(R.id.iv_download);
                    ImageView iv_share = customView.findViewById(R.id.iv_share);
                    final TextView tv_number_indicator = (TextView) customView.findViewById(R.id.tv_number_indicator);
                    tv_download_progress  = customView.findViewById(R.id.tv_download_progress);
                    pb_download = customView.findViewById(R.id.pb_download);
                    pb_download.setVisibility(View.INVISIBLE);
                    tv_download_progress.setVisibility(View.INVISIBLE);
                    ic_close.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //关闭图片浏览
                            MNImageBrowser.finishImageBrowser();
                        }
                    });
                    iv_more.setVisibility(View.GONE);
                    iv_more.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            FragmentActivity currentActivity = MNImageBrowser.getCurrentActivity();
                            ImageView currentImageView = MNImageBrowser.getCurrentImageView();
                            if (currentImageView != null && currentActivity != null) {
                                //showListDialog(currentActivity, currentImageView);
                            }
                        }
                    });
                    iv_download.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            downloadImageWithShare(context,list.get(index),false);
                        }
                    });
                    iv_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            downloadImageWithShare(context,list.get(index),true);
                        }
                    });
                    /*iv_delete.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //删除当前位置的图片
                            MNImageBrowser.removeCurrentImage();
                            //刷新指示器
                            tv_number_indicator.setText((MNImageBrowser.getCurrentPosition() + 1) + "/" + MNImageBrowser.getImageList().size());
                        }
                    });*/
                    tv_number_indicator.setText((index + 1) + "/" + imgSrcList.size());
                    MNImageBrowser.with(context)
                            //必须-当前位置
                            .setCurrentPosition(index)
                            //必须-图片加载用户自己去选择
                            .setImageEngine(new GlideImageEngine())
                            //必须（setImageList和setImageUrl二选一，会覆盖）-图片集合
                            .setImageList(imgSrcList)
                            //必须（setImageList和setImageUrl二选一，会覆盖）-设置单张图片
                            //.setImageUrl("xxx")
                            //非必须-图片切换动画
                            .setTransformType(transformType)
                            //非必须-指示器样式（默认文本样式：两种模式）
                            .setIndicatorType(indicatorType)
                            //设置隐藏指示器
                            .setIndicatorHide(false)
                            //设置自定义遮盖层，定制自己想要的效果，当设置遮盖层后，原本的指示器会被隐藏
                            .setCustomShadeView(showCustomShadeView ? customView : null)
                            //自定义ProgressView，不设置默认默认没有
                            .setCustomProgressViewLayoutID(showCustomProgressView ? R.layout.layout_custom_progress_view : 0)
                            //非必须-屏幕方向：横屏，竖屏，Both（默认：横竖屏都支持）
                            .setScreenOrientationType(screenOrientationType)
                            //非必须-图片单击监听
                            .setOnClickListener(new OnClickListener() {
                                @Override
                                public Boolean onClick(FragmentActivity activity, ImageView view, int position, String url) {
                                    //单击监听
                                    Log.i("Image", "onClick: ");
                                    if(customView.getVisibility()==View.VISIBLE){
                                        customView.setVisibility(View.INVISIBLE);
                                    }else{
                                        customView.setVisibility(View.VISIBLE);
                                    }
                                    //返回一个布尔值决定单击图片是否关闭浏览
                                    return false;
                                }
                            })

                            //非必须-图片长按监听
                            .setOnLongClickListener(new OnLongClickListener() {
                                @Override
                                public void onLongClick(FragmentActivity activity, ImageView imageView, int position, String url) {
                                    //长按监听
                                    Log.i("Image", "onLongClick: ");
                                    if(customView.getVisibility()==View.VISIBLE){
                                        customView.setVisibility(View.INVISIBLE);
                                    }else{
                                        customView.setVisibility(View.VISIBLE);
                                    }
                                }
                            })

                            //页面切换监听
                            .setOnPageChangeListener(new OnPageChangeListener() {
                                @Override
                                public void onPageSelected(int position) {
                                    //Log.i(TAG, "onPageSelected:" + position);
                                    if (tv_number_indicator != null) {
                                        tv_number_indicator.setText((position + 1) + "/" + MNImageBrowser.getImageList().size());
                                        tv_download_progress.setVisibility(View.INVISIBLE);
                                        pb_download.setVisibility(View.INVISIBLE);
                                    }
                                }
                            })
                             //全屏模式：默认全屏模式
                             .setFullScreenMode(true)
                             //打开
                             .show(imageView);

                }
            });
        }

        @Override
        public String toString() {
            return super.toString() + " '" + image_item_title.getText() + "'";
        }

    }

    public void downloadImageWithShare(final Context context, final String src, final Boolean isWithShare){
        AndPermission.with(context)
                .runtime()
                .permission(Permission.Group.STORAGE)
                .onGranted(new Action() {
                    @Override
                    public void onAction(Object data) {
                        //保存图片
                        /*String saveDir = isWithShare?SkinFileUtils.getCacheDir(context)+File.separator+"Images":Environment.getExternalStorageDirectory()+File.separator+ Environment.DIRECTORY_DCIM +File.separator+"ReadMeImages";*/
                        final String saveDir = Environment.getExternalStorageDirectory()+File.separator+ Environment.DIRECTORY_DCIM +File.separator+"readme_images";
                        final String cacheDir = SkinFileUtils.getCacheDir(context) + File.separator + "images";
                        final String fileName = FileUtils.get().getNameFromUrl(src);
                        File saveFile = new File(saveDir,fileName);
                        if(saveFile.exists()){
                            if (isWithShare){
                                shareImage(saveFile);
                            }else{
                                //询问是否重新下载，是就继续，否则return退出
                                new AlertDialog.Builder(MNImageBrowserActivity.getCurrentActivity())
                                        .setTitle("文件已存在！")
                                        .setMessage("是否重新下载？")
                                        .setNegativeButton("否", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        })
                                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                startDownload(src, saveDir,fileName,isWithShare);
                                            }
                                        })
                                        .show();
                            }
                        }else{
                            if(isWithShare) {
                                File cacheFile = new File(cacheDir, fileName);
                                if (cacheFile.exists()) {
                                    shareImage(cacheFile);
                                }else{
                                    startDownload(src, cacheDir,fileName,isWithShare);
                                }
                            }else{
                                startDownload(src, saveDir,fileName,isWithShare);
                            }
                        }

                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(Object data) {
                        Toast.makeText(context,"权限获取失败",Toast.LENGTH_SHORT).show();
                    }
                })
                .start();
    }

    private void startDownload(String src, String saveDir, String fileName, final Boolean isWithShare) {
        pb_download.setVisibility(View.VISIBLE);
        tv_download_progress.setVisibility(View.VISIBLE);
        FileUtils.get().download(src, saveDir,fileName, new FileUtils.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                //Toast.makeText(MyApplication.getContext(),"已保存到："+path,Toast.LENGTH_SHORT).show();

                //tv_download_progress.setText(R.string.image_download_success);
                Message msg = uiHandler.obtainMessage();
                msg.what=0;
                msg.obj = isWithShare;
                uiHandler.sendMessage(msg);
                if(isWithShare){
                    shareImage(file);
                }else {
                    MNImageBrowser.getCurrentActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));    // 发送广播，通知刷新图库的显示
                    Snackbar.make(tv_download_progress,"已保存到："+file.getPath(),Snackbar.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onDownloading(int progress) {
                Log.i("download", "onDownloading: "+progress);
                //Snackbar.make(iv_download,"下载中："+progress+"%",Snackbar.LENGTH_SHORT).show();
                //tv_download_progress.setText(context.getString(R.string.image_download_progress)+progress+"%");
                Message msg = uiHandler.obtainMessage();
                msg.what=1;
                msg.arg1=progress;
                msg.obj = isWithShare;
                uiHandler.sendMessage(msg);
                pb_download.setProgress(progress);
            }

            @Override
            public void onDownloadFailed() {
                //Toast.makeText(MyApplication.getContext(),"保存失败",Toast.LENGTH_SHORT).show();
                //Snackbar.make(tv_download_progress,"下载失败",Snackbar.LENGTH_SHORT).show();

                //tv_download_progress.setText(R.string.image_download_fail);
                Message msg = uiHandler.obtainMessage();
                msg.what=2;
                msg.obj = isWithShare;
                uiHandler.sendMessage(msg);
            }
        });
    }

    private void shareImage(File file) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("image/*");
        Uri uri;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(MNImageBrowser.getCurrentActivity(), "cn.leftshine.readme.fileprovider",file);
        }else{
            uri = Uri.fromFile(file);
        }
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent = Intent.createChooser(intent,"分享到：");
        MNImageBrowser.getCurrentActivity().startActivity(intent);
        //MNImageBrowser.getCurrentActivity().startActivityForResult(intent,0);
    }


    /*构造一个Handler，主要作用有：1）供非UI线程发送Message  2）处理Message并完成UI更新*/
    public Handler uiHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Boolean isWithShare = (Boolean)msg.obj;
            switch (msg.what){
                case 0:
                    tv_download_progress.setText(isWithShare?R.string.image_prepare_success:R.string.image_download_success);
                    break;
                case 1:
                    tv_download_progress.setText(isWithShare?mContext.getString(R.string.image_prepare_progress)+msg.arg1+"%":mContext.getString(R.string.image_download_progress)+msg.arg1+"%");
                    break;
                case 2:
                    tv_download_progress.setText(isWithShare?R.string.image_prepare_fail:R.string.image_download_fail);
                    break;
                default:
                    break;

            }
            return false;
        }
    });
}
